import sys
import threading
class Events:
	""" Class realize event subsystem. """
	def __init__(self, DEBUG = False):
		""" Initialize class. """
		self.DEBUG = DEBUG
		self._events = {}

	def Subscribe(self, Event, Function):
		""" Connect function to event. ( Event is "EVENT_NAME" ) """
		if not self._events.has_key(Event):
			# If it is first subscribe for this event
			# Create list in dict.
			self._events[Event] = list()
		try:
			# try to append in list
			self._events[Event].append(Function)
		except:
			if self.DEBUG:
				exc_info = sys.exc_info()[0]
				print "Exception in Events::Subscribe:"
				print "Class: ",exc_info[0]
				print "Error: ",exc_info[1]

	def Unsubscribe(self, Event, Function):
		""" Disconnect function from event. """
		if self._events.has_key(Event):
			try:
				self._events[Event].remove(Function)
			except:
				pass
	def Event(self, Event):
		""" Generate event. Call all connected functions. """
		if self.DEBUG:
			print Event.event, Event.userdata
		# DEBUG (REMOVE THIS STRING AFTER DEBUG)
		#print Event.event
		# DEBUG END
		if self._events.has_key(Event.event):
			try:
				for i in self._events[Event.event]:
					try:
						if Event.event != "ON_SYSTEM_SHUTDOWN":
							i(Event)
						else:
							i()
					except:
						if self.DEBUG:
							print "Exception in EventHandler"
							print i
							print sys.exc_info()
			except:
				if self.DEBUG:
					exc_info = sys.exc_info()
        	                	print "Exception in Events::Event:"
	        	                print "Class: ",exc_info[0]
        	        	        print "Error: ",exc_info[1]
